<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/17
 * Time: 9:37
 */

namespace app\index\controller;

use app\index\model\FoodAttribute;
use app\index\model\Home;
use app\index\model\Order;
use app\index\model\ShopCar;
use app\index\model\ShopEvaluate;
use app\index\model\ShopList;
use app\index\model\ShopCategory;
use app\index\model\ShopFoods;
use app\index\model\FoodSpec;

class ShopController extends BaseController
{


    public function shopList()
    {
        $sort = (int)input('post.sort');
        $page = (int)input('post.page');
        $number = (int)input('post.number');
        switch ($sort) {
            case 0;
                $order = (int)input('post.status') ? 'sort desc' : 'sort asc';
                $data = $this->shopSelect($order, $page, $number);
                foreach ($data as $k => $v) {
                    $data[$k]['distance'] = '';
                }
                break;
            case 1;
                $order = (int)input('post.status') ? SORT_DESC : SORT_ASC;
                $longitude = input('post.longitude');
                $latitude = input('post.latitude');
                if ($latitude && $latitude) {
                    $data = $this->shopSelect('sort desc', $page, $number);
                    if ($data) {
                        foreach ($data as $k => $v) {
                            $data[$k]['distance'] = $this->getDistance($longitude, $latitude, $v['longitude'], $v['latitude'], 2);
                        }
                        $data = $this->arraySort($data, 'distance', $order);
                    }
                } else {
                    $data = '';
                }
                break;
            case 2;
                $order = (int)input('post.status') ? 'order_number desc' : 'order_number asc';
                $data = $this->shopSelect($order, $page, $number);
                foreach ($data as $k => $v) {
                    $data[$k]['distance'] = '';
                }
                break;
            case 3;
                $order = (int)input('post.status') ? 'evaluate desc' : 'evaluate asc';
                $data = $this->shopSelect($order, $page, $number);
                foreach ($data as $k => $v) {
                    $data[$k]['distance'] = '';
                }
                break;
            default;
                $data = '';
                break;
        }
        if (empty($data)) {
            return json(['code' => 0, 'msg' => '无数据']);
        }
        return json(['code' => 1, 'msg' => '返回成功', 'data' => $data]);
    }

    private function shopSelect($order, $page, $number)
    {
        $dataAll = ShopList::where('status', 1)->order($order)
            ->field('id,shop_name,shop_image,order_number,evaluate,longitude,latitude')
            ->limit(($page - 1) * $number, $number)
            ->select();
        foreach ($dataAll as $k=>$v){
            $dataAll[$k]['shop_image'] = $this->url.$v['shop_image'];
        }
        return $dataAll->toArray();
    }
    //店铺详情表
    public function shopInfo()
    {
        $shop_id = input('post.shop_id');
        $data = ShopList::where('id', $shop_id)->find();
        if (empty($data)) {
            return json(['code' => 0, 'msg' => '无数据']);
        }
        $data['shop_image'] = $this->url.$data['shop_image'];
        $data['shop_ad_image'] = $this->url.$data['shop_ad_image'];
        if ($data['business_hours']) {
            $data['business_hours'] = $this->shopTimeRestore($data['business_hours']);
        }else{
            $data['business_hours'] = '';
        }
        return json(['code' => 1, 'msg' => '返回成功', 'data' => $data]);
    }

    public function shopCategory()
    {
        $shop_id = input('post.shop_id');
        $data = ShopCategory::where('shop_id', $shop_id)->where('status', 1)->order('sort asc')->select()->toArray();
        if (empty($data)) {
            return json(['code' => 0, 'msg' => '无数据']);
        }
        return json(['code' => 1, 'msg' => '返回成功', 'data' => $data]);
    }

    public function shopFoods()
    {
        $shop_id = input('post.shop_id');
        $category_id = input('post.category_id');
        $data = ShopFoods::where('shop_id', $shop_id)->where('category_id', $category_id)->select()->toArray();
        if (empty($data)) {
            return json(['code' => 0, 'msg' => '无数据']);
        }
        foreach ($data as $key=>$value){
            $data[$key]['image'] = $this->url.$value['image'];
        }
        return json(['code' => 1, 'msg' => '返回成功', 'data' => $data]);
    }

    public function foodSpec()
    {
        $food_id = input('post.food_id');
        $data = FoodSpec::with(['foodAttribute' => function ($query) {
            $query->field('id,spec_id,attribute_name,price');
        }])->where('food_id', $food_id)->select()->toArray();
        if (empty($data)) {
            return json(['code' => 0, 'msg' => '无数据']);
        }
        $price = [];
        foreach ($data as $k => $v) {
            $price[] = $v['food_attribute'][0]['price'];
        }
        $ret = ShopFoods::where('id', $food_id)->field('category_id,price')->find();
        $category = ShopCategory::where('id', $ret['category_id'])->field('spike')->find();
        if ($category['spike'] == 1) {
            $ret = ShopFoods::where('id', $food_id)->field('spike_price')->find();
            $ret['price'] = $ret['spike_price'];
        }
        $price = array_sum($price) + $ret['price'];
        if (!$price) {
            $price = $ret['price'];
        }
        return json(['code' => 1, 'msg' => '返回成功', 'data' => $data, 'price' => $price]);
    }

    //购物车新增
    public function carAdd()
    {
        $user_id = (int)input('post.user_id');
        $shop_id = (int)input('post.shop_id');
        $category_id   = (int)input('post.category_id');
        $food_id = (int)input('post.food_id');
        $spec_id = (array)input('post.spec_id');
        $number = (int)input('post.number');
        if (empty($user_id)) {
            return json(['code' => 2, 'msg' => '用户ID不能为0']);
        }
        if (!is_array($spec_id)) {
            return json(['code' => 2, 'msg' => 'spec_id为数组']);
        }
        $spike = ShopCategory::where('id',$category_id)->field('id,spike')->find();
        $food = ShopFoods::where('id', $food_id)->find();
        $spec = '';
        $price = $food['price'];
        if (!empty($spec_id)) {
            $specAll = FoodAttribute::all($spec_id);
            $spec = '';
            $price = [];
            foreach ($specAll as $item) {
                if (empty($spec)) {
                    $spec = $item['attribute_name'];
                } else {
                    $spec = $spec . "+" . $item['attribute_name'];
                }
                $price[] = $item['price'];
            }
            $price = array_sum($price);
        }
        $insert = [
            'user_id' => $user_id,
            'shop_id' => $shop_id,
            'food_id' => $food['id'],
            'spec_id' => implode(',', $spec_id),
            'food_name' => $food['food_name'],
            'image' => $food['image'],
            'spec' => $spec,
            'number' => $number,
            'price' => $price,
            'spike' => $spike['spike']
        ];
        $find = ShopCar::where('user_id',$insert['user_id'])->where('shop_id',$insert['shop_id'])
            ->where('food_id',$insert['food_id'])->where('spec_id',$insert['spec_id'])->find();
        if ($find){
            $ins = ShopCar::update(['number'=>$find['number']+$insert['number']],['id'=>$find['id']]);
        }else{
            $ins = ShopCar::create($insert);
        }
        if (!$ins) {
            return json(['code' => 0, 'msg' => '新增失败']);
        }
        return json(['code' => 1, 'msg' => '新增成功']);
    }

    //购物车修改
    public function carEdit()
    {
        $user_id = (int)input('post.user_id');
        $shop_id = (int)input('post.shop_id');
        $car_id = (int)input('post.car_id');
        $status = (int)input('post.status');
        if (empty($user_id)) {
            return json(['code' => 2, 'msg' => '用户ID不能为0']);
        }
        if (empty($car_id)) {
            return json(['code' => 2, 'msg' => '购物车ID不能为0']);
        }
        if (empty($status)) {
            return json(['code' => 2, 'msg' => '状态不能为空']);
        }
        $car = ShopCar::where('id', $car_id)->field('id,number')->find()->toArray();
        if ($status == 1) {
            $car['number']++;
            $car = ShopCar::update($car);
        } else {
            if ($car['number'] <= 1) {
                $car = ShopCar::destroy($car);
            } else {
                $car['number']--;
                $car = ShopCar::update($car);
            }
        }
        if ($car) {
            $car = ShopCar::where('user_id', $user_id)->where('shop_id', $shop_id)->select()->toArray();
            $count = count($car);
            $total = [];
            foreach ($car as $k => $v) {
                $total[] = $v['price'] * $v['number'];
            }
            $total = array_sum($total);
            return json(['code' => 1, 'msg' => '修改成功', 'total' => $total, 'count' => $count]);
        } else {
            return json(['code' => 0, 'msg' => '修改失败']);
        }
    }

    //购物车列表
    public function carList()
    {
        $user_id = (int)input('post.user_id');
        $shop_id = (int)input('post.shop_id');
        $data['list'] = ShopCar::where('user_id', $user_id)->where('shop_id', $shop_id)
            ->field('id,food_name,spec,number,price')->select()->toArray();
        if (empty($data['list'])) {
            return json(['code' => 0, 'msg' => '无数据']);
        }
        $total = [];
        foreach ($data['list'] as $k => $v) {
            $total[] = $v['price'] * $v['number'];
        }
        $total = array_sum($total);
        return json(['code' => 1, 'msg' => '返回成功', 'data' => $data, 'total' => $total]);
    }

    //购物车清除
    public function carDel()
    {
        $user_id = (int)input('post.user_id');
        $shop_id = (int)input('post.shop_id');
        $del = ShopCar::where('user_id', $user_id)->where('shop_id', $shop_id)->delete();
        if (!$del) {
            return json(['code' => 0, 'msg' => '删除失败']);
        }
        return json(['code' => 1, 'msg' => '删除成功']);
    }

    //评论列表
    public function shopEvaluate()
    {
        $shop_id = (int)input('post.shop_id');
        $status = input('post.status') ? ['status' => (int)input('post.status')] : '';
        $page = (int)input('post.page');
        $number = (int)input('post.number');
        $data['list'] = ShopEvaluate::with(['user' => function ($query) {
            $query->field('id,wx_nickname,wx_image');
        }])->where('shop_id', $shop_id)
            ->where($status)->limit(($page - 1) * $number, $number)->select()->toArray();
        $start = ShopList::where('id',$shop_id)->value('evaluate');
        $taste = [];
        foreach ($data['list'] as $k => $v) {
            $taste[] = $v['taste'];
            if ($v['imgs']) {
                $data['list'][$k]['imgs'] = explode(',', $v['imgs']);
                foreach ($data['list'][$k]['imgs'] as $key=>$value){
                    $data['list'][$k]['imgs'][$k] = $this->url.$value;
                }
            } else {
                $data['list'][$k]['imgs'] = [];
            }
        }
        $data['status']['total'] = ShopEvaluate::where('shop_id', $shop_id)->count();
        $data['status']['good'] = ShopEvaluate::where('shop_id', $shop_id)->where('status', 1)->count();
        $data['status']['in'] = ShopEvaluate::where('shop_id', $shop_id)->where('status', 2)->count();
        $data['status']['diff'] = ShopEvaluate::where('shop_id', $shop_id)->where('status', 3)->count();
        $data['start'] = $start;
        if (count($taste)){
            $data['taste'] = round(array_sum($taste) / count($taste), 1);
        }else{
            $data['taste'] = 5;
        }
        return json(['code' => 1, 'msg' => '返回成功', 'data' => $data]);
    }

    //菜品详情
    public function foodInfo()
    {
        $food_id = (int)input('post.food_id');
        $data = ShopFoods::where('id', $food_id)->field('food_name,price,quality,introduce,images')->find()->toArray();
        if (empty($data)) {
            return json(['code' => 0, 'msg' => '无数据']);
        }
        $data['images'] = explode(",", $data['images']);
        foreach ($data['images'] as $key=>$value){
            $data['images'][$key] = $this->url.$value;
        }
        return json(['code' => 1, 'msg' => '返回成功', 'data' => $data]);
    }

    public function evaluateSave(){
        $user_id = (int)input('post.user_id');
        $shop_id = (int)input('post.shop_id');
        $order_no = input('post.order_no');
        $images  = (array)input('post.images');
        $content = trim(input('post.content'));
        $service = (int)input('post.service');
        $taste = (int)input('post.taste');
        $degree = (int)input('post.degree');
        if (!$user_id){
            return json(['code'=>0,'msg'=>'user_id不能为空']);
        }
        if (!$order_no){
            return json(['code'=>0,'msg'=>'订单号不能为空']);
        }
        if (!$shop_id){
            return json(['code'=>0,'msg'=>'shop_id不能为空']);
        }
        if (!$service){
            return json(['code'=>0,'msg'=>'service不能为空']);
        }
        if (!$taste){
            return json(['code'=>0,'msg'=>'taste不能为空']);
        }
        if (!$degree){
            return json(['code'=>0,'msg'=>'degree不能为空']);
        }
        $grade = $service + $taste + $degree;
        $start = round(($grade)/3,1);
        $insert=[
            'user_id'=>$user_id,
            'shop_id'=>$shop_id,
            'order_no'=>$order_no,
            'imgs'=>implode(',',$images),
            'content'=>$content,
            'service'=>$service,
            'taste'=>$taste,
            'degree'=>$degree,
            'start'=>$start,
        ];
        if ($grade <= 5){
            $insert['status'] = 3;
        }elseif($grade >5 && $grade<=10){
            $insert['status'] = 2;
        }elseif($grade >10){
            $insert['status'] = 1;
        }
        $ret = ShopEvaluate::create($insert);
        $order = Order::update(['order_status'=>2],['order_no'=>$order_no]);
        if ($ret && $order){
            return json(['code'=>1,'msg'=>'评论成功']);
        }else{
            return json(['code'=>0,'msg'=>'评论失败']);
        }

    }



    public function home(){
        $data = Home::get(1);
        $data['image'] = $this->url.$data['image'];
        return json(['code'=>1,'msg'=>'返回成功','data'=>$data]);
    }


}